package com.asy.ui.base;

 
import java.lang.ref.SoftReference;  
import java.util.HashMap;    
import java.util.Hashtable;
import java.util.Map;

import com.helper.ImageHelper;
import com.xinzhang.base.ThreadManager;

import android.graphics.Bitmap;  
import android.os.Handler;  
import android.os.Message;  
import android.util.Log;
  
public class AsyncImageLoader {  
  
     private Map<String, SoftReference<Bitmap>> imageCache;  
        
         public AsyncImageLoader() {  
             imageCache = new HashMap<String, SoftReference<Bitmap>>();  
         }  
         public Bitmap loadDrawable(final String imageUrl, final ImageCallback imageCallback) {  
             if (imageCache.containsKey(imageUrl)) {  
                 SoftReference<Bitmap> softReference = imageCache.get(imageUrl);  
                 Bitmap bitmap = softReference.get();  
                 if (bitmap != null) {  
                     return bitmap;  
                 }  
             }  
             final Handler handler = new Handler() {  
                 public void handleMessage(Message message) {  
                     imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);  
                 }  
             };  
             ThreadManager.GetThreadPool().execute(new Runnable(){public void run() {
            	// TODO Auto-generated method stub
            	 try {
            		 Thread.sleep(500);
            		 if(!imageCache.containsKey(imageUrl))
            		 {
            			 Bitmap bitmap = loadImageFromUrl(imageUrl);  
            			 imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap)); 
            			 Message message = handler.obtainMessage(0, bitmap);  
                         handler.sendMessage(message);  
            		 }
                     
				} catch (Exception e) {
					// TODO: handle exception
					Log.w("ThreadError", e.toString());
				}
             }});
//             new Thread() {  
//                 public void run() {  
//                     Bitmap bitmap = loadImageFromUrl(imageUrl);  
//                     imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));  
//                     Message message = handler.obtainMessage(0, bitmap);  
//                     handler.sendMessage(message);  
//                 }  
//             }.start();  
             return null;  
         }  
        public static Bitmap loadImageFromUrl(String url) {  
          
            return ImageHelper.loadBitmap(url);
        }  
        
         public interface ImageCallback {  
             public void imageLoaded(Bitmap bitmap, String imageUrl);  
         }  
  
}  